//
//  CSIdAuthViewController.m
//  ZSYH
//
//  Created by 主事丫环 on 2019/7/8.
//  Copyright © 2019 魏堰青. All rights reserved.
//

#import "CSIdAuthViewController.h"
#import "JYBDBankCardVC.h"
#import "MBProgressHUD.h"
#import "JYBDIDCardVC.h"
#import "DISBBuildingViewController.h"
#import "TabBarViewController.h"
#import <AipOcrSdk/AipOcrSdk.h>
#import "BBuildingShopViewController.h"

@interface CSIdAuthViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    // 默认的识别失败的回调
    void (^_failHandler)(NSError *);
}

@property (nonatomic, strong) UIScrollView *scrollV;
@property (nonatomic, strong) UILabel *tipsL;
@property (nonatomic, strong) UIImageView *upImage;
@property (nonatomic, strong) UIImageView *dowImage;
@property (nonatomic, strong) UIImageView *holdIdIV;
@property (nonatomic, strong) UIButton *upBut;
@property (nonatomic, strong) UIButton *dowBUt;
@property (nonatomic, strong) UIButton *holdIdB;
@property (nonatomic, strong) UIButton *nextB;
@property (nonatomic, strong) NSString *cardstr;
@property (nonatomic, strong) NSString *cardname;

@end

@implementation CSIdAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    //授权方法1：在此处填写App的Api Key/Secret Key
    [[AipOcrService shardService] authWithAK:@"ms8H0dPSnKFmQs4nppHNSlrZ" andSK:@"3wKG7naZHvqzhAHeMRvTwZgT0REHxzCI"];
    
    [self configCallback];
}

- (void)setUI {
    
    self.title = @"身份认证";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    
    _scrollV = [UIScrollView new];
    _scrollV.frame = CGRectMake(0, 0, ScreenW, ScreenH);
    _scrollV.contentSize = CGSizeMake(ScreenW, ScreenH+100+107);
    [self.view addSubview:_scrollV];
    
    _tipsL = [UILabel new];
    _tipsL.text = @"请上传您的中国第二代居民身份证原件";
    _tipsL.textColor = [UIColor grayColor];
    _tipsL.font = [UIFont systemFontOfSize:15];
    _tipsL.textAlignment = NSTextAlignmentCenter;
    [_scrollV addSubview:_tipsL];
    [_tipsL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(20);
        make.width.mas_equalTo(ScreenW-40);
        make.height.mas_equalTo(40);
    }];
    
    _upImage = [UIImageView new];
    _upImage.userInteractionEnabled = YES;
    _upImage.image = [UIImage imageNamed:@"shenfenzhengZM"];
    [_scrollV addSubview:_upImage];
    [_upImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tipsL.mas_bottom).with.offset(20);
        make.width.mas_equalTo(312);
        make.left.mas_equalTo((ScreenW-312)/2);
        make.height.mas_equalTo(175);
    }];
    
    _upBut = [UIButton new];
    [_upBut setBackgroundImage:[UIImage imageNamed:@"shenfenzhengAction"] forState:(UIControlStateNormal)];
    [_upBut addTarget:self action:@selector(upAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_upImage addSubview:_upBut];
    [_upBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(30);
        make.centerX.mas_equalTo(_upImage.centerX);
        make.width.mas_equalTo(72);
        make.height.mas_equalTo(72);
    }];
    
    _dowImage = [UIImageView new];
    _dowImage.userInteractionEnabled = YES;
    _dowImage.image = [UIImage imageNamed:@"shenfenzhengFM"];
    [_scrollV addSubview:_dowImage];
    [_dowImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_upImage.mas_bottom).with.offset(20);
        make.width.mas_equalTo(312);
        make.left.mas_equalTo((ScreenW-312)/2);
        make.height.mas_equalTo(175);
    }];
    
    _dowBUt = [UIButton new];
    [_dowBUt setBackgroundImage:[UIImage imageNamed:@"shenfenzhengAction"] forState:(UIControlStateNormal)];
    [_dowBUt addTarget:self action:@selector(dowAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_dowImage addSubview:_dowBUt];
    [_dowBUt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(30);
        make.centerX.mas_equalTo(_dowImage.centerX);
        make.width.mas_equalTo(72);
        make.height.mas_equalTo(72);
    }];
    
    //    _holdIdIV = [UIImageView new];
    //    _holdIdIV.userInteractionEnabled = YES;
    //    _holdIdIV.image = [UIImage imageNamed:@"组 3029"];
    //    [_scrollV addSubview:_holdIdIV];
    //    [_holdIdIV mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.equalTo(_dowImage.mas_bottom).with.offset(20);
    //        make.width.mas_equalTo(312);
    //        make.left.mas_equalTo((ScreenW-312)/2);
    //        make.height.mas_equalTo(282);
    //    }];
    
    //    _holdIdB = [UIButton new];
    //    [_holdIdB setBackgroundImage:[UIImage imageNamed:@"shenfenzhengAction"] forState:(UIControlStateNormal)];
    //    [_holdIdB addTarget:self action:@selector(holdIdBClick:) forControlEvents:(UIControlEventTouchUpInside)];
    //    [_holdIdIV addSubview:_holdIdB];
    //    [_holdIdB mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.mas_equalTo(100);
    //        make.centerX.mas_equalTo(_holdIdIV.centerX);
    //        make.width.mas_equalTo(72);
    //        make.height.mas_equalTo(72);
    //    }];
    
    _nextB = [UIButton new];
    [_nextB setTitle:@"下一步" forState:(UIControlStateNormal)];
    [_nextB addTarget:self action:@selector(baocunAction:) forControlEvents:(UIControlEventTouchUpInside)];
    _nextB.layer.cornerRadius = 3;
    [_nextB setBackgroundColor:zhutiColor];
    [_scrollV addSubview:_nextB];
    [_nextB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_dowImage.mas_bottom).with.offset(20);
        make.left.mas_equalTo(30);
        make.width.mas_equalTo(ScreenW-60);
        make.height.mas_equalTo(50);
    }];
    self.dowBUt.hidden = YES;
    self.holdIdB.hidden = YES;
}

- (void)configCallback {
    __weak typeof(self) weakSelf = self;
    
    _failHandler = ^(NSError *error){
        NSLog(@"%@", error);
        NSString *msg = [NSString stringWithFormat:@"%li:%@", (long)[error code], [error localizedDescription]];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[[UIAlertView alloc] initWithTitle:@"识别失败" message:msg delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
        }];
    };
}

#pragma mark - 身份证正面识别
- (void)upAction:(UIButton *)sender {
    kWeakSelf;
    UIViewController * vc = [AipCaptureCardVC ViewControllerWithCardType:CardTypeLocalIdCardFont andImageHandler:^(UIImage *image) {
        [[AipOcrService shardService] detectIdCardFrontFromImage:image withOptions:nil successHandler:^(id result){
            [weakSelf frontResultDealAction:result image:image];
        } failHandler:_failHandler];
    }];
    [self presentViewController:vc animated:YES completion:nil];
    
}

- (void)frontResultDealAction:(id)result image:(UIImage *)image{
    KMyLog(@"身份证正面信息:%@",result);
    //主线程
    kWeakSelf;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSString *imageStatus = [result objectForKeyNotNil:@"image_status"];
            if ([imageStatus isEqualToString:@"normal"]) {
                //获得完整的身份证信息
                weakSelf.upImage.image = image;
                weakSelf.cardstr = result[@"words_result"][@"公民身份号码"][@"words"];
                weakSelf.cardname = result[@"words_result"][@"姓名"][@"words"];
                weakSelf.upBut.hidden = YES;
                weakSelf.dowBUt.hidden = NO;
            } else {
                ShowToastWithText(@"当前图片不合规，请重新选择");
            }
        } else {
            ShowToastWithText(@"获取图片信息失败，请重试");
        }
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    });
}

#pragma mark - 身份证反面识别
- (void)dowAction:(UIButton *)sender {
    kWeakSelf;
    UIViewController * vc = [AipCaptureCardVC ViewControllerWithCardType:CardTypeLocalIdCardBack andImageHandler:^(UIImage *image) {
        [[AipOcrService shardService] detectIdCardFrontFromImage:image withOptions:nil successHandler:^(id result){
            [weakSelf reverseResultDealAction:result image:image];
        }failHandler:_failHandler];
    }];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)reverseResultDealAction:(id)result image:(UIImage *)image{
    KMyLog(@"身份证反面信息:%@",result);
    kWeakSelf;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSString *imageStatus = [result objectForKeyNotNil:@"image_status"];
            if ([imageStatus isEqualToString:@"reversed_side"]) {
                //获得完整的身份证信息
                weakSelf.dowImage.image = image;
                weakSelf.dowBUt.hidden = YES;
                weakSelf.holdIdB.hidden = NO;
            } else {
                ShowToastWithText(@"当前图片不合规，请重新选择");
            }
        } else {
            ShowToastWithText(@"获取图片信息失败，请重试");
        }
        [weakSelf dismissViewControllerAnimated:YES completion:^{}];
    });
}

#pragma mark - 手持身份证
- (void)holdIdBClick:(UIButton *)sender {
    
    UIImagePickerController *pick = [[UIImagePickerController alloc]init];
    pick.delegate = self;
    [UIAlertController showPhotoAlerControllerPicker:pick controller:self sourceView:nil];
}

//imagePicker代理事件
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.holdIdIV.image = image;
        self.upBut.hidden = YES;
        self.dowBUt.hidden = YES;
        self.holdIdB.hidden = NO;
    });
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//下一步
- (void)baocunAction:(UIButton *)sender {
    
    if (!_upBut.hidden) {
        ShowToastWithText(@"请拍摄身份证正面照");
        return;
    }
    
    if (!_dowBUt.hidden) {
        ShowToastWithText(@"请拍摄身份证反面照");
        return;
    }
    
    NSMutableArray *muarr = [NSMutableArray arrayWithCapacity:1];
    [muarr addObject:_upImage];
    [muarr addObject:_dowImage];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"id_card"] = _cardstr;
    param[@"name"] = _cardname;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    kWeakSelf;
    
    [NetWorkTool UploadPicWithUrl:upphoneIdracd param:param key:@"image" image:muarr withSuccess:^(id dic) {
        
        NSString *errorCode = dic[@"errorCode"];
        NSString *msg = dic[@"msg"];
        if ([errorCode isEqualToString:@"002"]) {
            ShowToastWithText(msg);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            return ;
        }
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        ShowToastWithText(@"上传成功");
        
        if ([self.iscenter isEqualToString:@"center"]) {
            [self.navigationController popViewControllerAnimated:YES];
            return ;
        }

        NSString *sss =[USER_DEFAULT objectForKey:@"level"];
        
        if ([weakSelf.iscenter isEqualToString:@"center"]) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
            return;
        }
        
        if ([sss isEqualToString:@"1"]) {
            //去展示
            TabBarViewController *tabbar = [[TabBarViewController alloc]init];
            [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;
            
        }  else {
            if (strIsEmpty(weakSelf.isstr)) {
                TabBarViewController *tabbar = [[TabBarViewController alloc]init];
                [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;
                //绑定
                //[self.navigationController pushViewController:[BBuildingShopViewController new] animated:YES];
            } else {
                if ([sss isEqualToString:@"2"]) {
                    //去展示b有收益
                    TabBarViewController *tabbar = [[TabBarViewController alloc]init];
                    [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;
                } else {
                    //去展示b没收益
                    TabBarViewController *tabbar = [[TabBarViewController alloc]init];
                    [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;
                }
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

@end
